#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：AutoMagic 
@File    ：element_handlers.py
@Author  ：赵加响
@Date    ：2022/12/29 15:21 
@Desc    ：
"""
import time

from selenium.common.exceptions import WebDriverException, NoSuchElementException, ElementNotVisibleException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys


class ElementHandlers:

    def is_ready_state_complete(self, driver):
        try:
            # 获取页面的状态
            # execute_script执行js代码
            ready_state = driver.execute_script("return document.readyState")
        except WebDriverException:
            # 如果有Driver的问题，执行js就会失败，就直接掉过
            ready_state = None

        return ready_state == 'complete'

    def is_element_display(self, driver, xpath_expression):
        try:
            driver.find_element(By.XPATH, xpath_expression)
            return True
        except NoSuchElementException:
            # 发生了NoSuchElementException异常，元素没有找到
            return False

    def wait_for_ready_state_complete(self, driver, timeout=10):
        """
        等待当前页面刷新完成
        :param driver:
        :param timeout:
        :return:
        """
        # 开始时间
        start_ms = time.time() * 1000
        # 结束时间
        stop_ms = start_ms + (timeout * 1000)

        ready = False

        while ready is False:
            now_ms = time.time() * 1000
            if stop_ms >= now_ms:
                ready = self.is_ready_state_complete(driver)
            else:
                raise Exception(f'打开网页时，页面元素{timeout}秒没有加载完成')

        return True

    def element_get(self, driver, xpath_expression, timeout=10):
        """
        获取单个元素
        :param driver:
        :param xpath_expression:
        :param timeout:
        :return:
        """
        # 开始时间
        start_ms = time.time() * 1000
        # 结束时间
        stop_ms = start_ms + (timeout * 1000)

        is_display = False

        while is_display is False:
            now_ms = time.time() * 1000
            if stop_ms >= now_ms:
                is_display = self.is_element_display(driver, xpath_expression)
            else:
                raise ElementNotVisibleException(f'元素没有找到，XPATH表达式{xpath_expression}')

        element = driver.find_element(by=By.XPATH, value=xpath_expression)
        time.sleep(0.5)
        return element

    def element_to_url(self, driver, url):
        """
        跳转地址
        :param driver:浏览器驱动
        :param url:跳转的地址
        :return:
        """
        driver.get(url)
        # 等待页面元素加载完成
        self.wait_for_ready_state_complete(driver)

    def element_fill_value(self, driver, xpath_expression, fill_value):
        """
        输入值
        :param driver:
        :param xpath_expression:
        :param fill_value:
        :return:
        """
        element = self.element_get(driver, xpath_expression)
        element.clear()

        if type(fill_value) is int or type(fill_value) is float:
            fill_value = str(fill_value)

        # 不是以\n结尾，直接填值
        if not fill_value.endswith('\n'):
            element.send_keys(fill_value)
        else:
            fill_value = fill_value[:-1]
            element.send_keys(fill_value)
            element.send_keys(Keys.RETURN)

    def element_click(self, driver, xpath_expression):
        """
        点击事件
        :param driver:
        :param xpath_expression:
        :return:
        """
        element = self.element_get(driver, xpath_expression)
        element.click()

    def upload(self, driver, xpath_expression, file_path):
        """
        文件上传
        :param driver:
        :param xpath_expression:
        :param file_path: 图片路径
        :return:
        """
        element = self.element_get(driver, xpath_expression)
        return element.send_keys(file_path)

    def wait_login_success(self, driver, xpath_expression):
        """

        :param driver:
        :param xpath_expression:
        :return:
        """
        display = False
        while display is False:
            display = self.is_element_display(driver, xpath_expression)
